# define _CRT_SECURE_NO_WARNINGS 1
#include "List.h"

ListNode* ListInit()
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		return NULL;
	}
	else
	{
		newnode->next = newnode;
		newnode->prev = newnode;
	}
	return newnode;
}


ListNode* BuyListNode(LTDataType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	newnode->next = NULL;
	newnode->prev = NULL;
	newnode->data = x;
	return newnode;
}


void ListPrint(ListNode* phead)
{
	ListNode* cur = phead->next;
	printf("head->");
	while (cur != phead)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("head\n");
}


void ListPushBack(ListNode* phead, LTDataType x)
{
	assert(phead);
	ListNode* newnode = BuyListNode(x);
	ListNode* tail = phead->prev;
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;
}


void ListPushFront(ListNode* phead, LTDataType x)
{
	assert(phead);
	ListNode* newnode = BuyListNode(x);
	ListNode* prev = phead->next;
	prev->prev = newnode;
	newnode->next = prev;
	newnode->prev = phead;
	phead->next = newnode;
}


void ListPopBack(ListNode* phead)
{
	assert(phead && phead->next);
	ListNode* tail = phead->prev;
	tail->prev->next = phead;
	phead->prev = tail->prev;
	free(tail);
	tail = NULL;
}


void ListPopFront(ListNode* phead)
{
	assert(phead && phead->next);
	ListNode* head = phead->next;
	head->next->prev = phead;
	phead->next = head->next;
	free(head);
	head = NULL;
}


ListNode* ListFind(ListNode* phead, LTDataType x)
{
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		if (x == cur->data)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}


void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* newnode = BuyListNode(x);
	ListNode* prev = pos->prev;
	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;

}


void ListErase(ListNode* pos)
{
	assert(pos);
	ListNode* tail = pos->next;
	ListNode* head = pos->prev;
	head->next = tail;
	tail->prev = head;
	free(pos);
	pos = NULL;
}


void ListDestory(ListNode* phead)
{
	ListNode* cur = phead->next;
	while (cur)
	{
		ListNode* tail = cur->next;
		free(cur);
		cur = tail;
	}
	free(phead);
	phead = NULL;
}